if [ "$1" = "-r" ]; then
  
  if [ "$#" -gt 2 ]; then
    echo "     Incorrect input format. Multiple item search should be enclosed in ' '"
    exit
  else
    #creates new tempfiles
    touch temp.$LOGNAME.rem
    touch remtemp.$LOGNAME.rem
    #searches for all remaining items and places it in remtemp
    grep -i "|-" ushop.$LOGNAME > remtemp.$LOGNAME.rem
    #user presses enter 
    
    if [ "$2" = "" ]; then
       awk -F "|" '{printf"%6d. %-30s %14.2f\n" ,NR, $1, $2 }' remtemp.$LOGNAME.rem
       
       if [ $(cat remtemp.$LOGNAME.rem  | wc -l  | cut -d' ' -f1) -eq 0 ]; then 
          echo "     There are no items to remaining items to delete"
          exit
       else
	  echo -n "     Delete all items above (y/n)? "
	  read input
	  
	  if [ "$yn" = "y" ]; then
             grep -v '|-' ushop.$LOGNAME | cat > ushop.$LOGNAME
             echo "     All items in your to-buy list have been deleted"
       	  else
	     exit	
          fi		
       
       fi
       
            
     #searches matching items for multiple queries
    else
      
      echo $2 > wc.$LOGNAME.rem
      wordnum=0
      wordnum=$(wc -w wc.$LOGNAME.rem | cut -d' ' -f1)
      while [ $wordnum -gt 0 ]
      do
        item=$( echo $2 | cut -d' ' -f$wordnum )
        grep -i "$item" remtemp.$LOGNAME.rem >> temp.$LOGNAME.rem
        wordnum=`expr $wordnum - 1`
      done
      #displays matching items
      echo ""
      awk -F "|" '{printf"%6d. %-30s %14.2f\n" ,NR, $1, $2 }' temp.$LOGNAME.rem
    
      if [ $(cat temp.$LOGNAME.rem  | wc -l  | cut -d' ' -f1) -eq 0 ]; then 	          
        echo "     There are no remaining items that matches search"
        exit  	
      else 	
        echo ""
        echo -n '     Indicate item number you want to delete (enter deletes everything): '
        #user enters item number to be deleted
        read input
           
	   if  echo $input | grep '\<[0-9]*\>' > /dev/null; then
              item=$(cat temp.$LOGNAME.rem | head -$input | tail -1 | cut -d'|' -f1 )
              origitem=$(grep "$item" ushop.$LOGNAME | cut -d'|' -f1 )
              origitemnum=$(grep -n "$origitem" ushop.$LOGNAME | cut -d'|' -f1 | cut -d':' -f1)
              echo -n "     Delete the item \"$origitem\" (y/n)? "
              read yn
                 
		 if [ "$yn" = "y" ]; then
                    sed "${input}d" temp.$LOGNAME.rem | cat > temp.$LOGNAME.rem
                    sed "${origitemnum}d" ushop.$LOGNAME | cat > ushop.$LOGNAME
                    echo '     Item deleted.'
                 else
                    exit
                 fi
		 
           else
               exit
           fi
      fi	   
    fi   
   fi
fi

#removes tempfiles
rm temp.$LOGNAME.rem
rm remtemp.$LOGNAME.rem
  
